package cn.hh.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

// @Component/*实例化到spring容器；登录拦截*/
public class LoginIntercept implements HandlerInterceptor{
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*获取token*/
        String token = request.getHeader("token");
        /*判断是否为空*/
        if (!StringUtils.isEmpty(token)){
            /*不为空就获取redis中的token判断是否存在*/
            Object redisToken = redisTemplate.opsForValue().get(token);
            if (redisToken!=null){
                /*如果存在就刷新过期时间，保证用户浏览时一直处于登陆状态*/
                redisTemplate.opsForValue().set(token,redisToken ,30 , TimeUnit.MINUTES );
                /*刷新后放行*/
                return true;
            }
        }
        /*为空就放行*/
        /*放行前设置返回前端的信息，搞不懂意思固定写法*/
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }

}
